<template>
  <div class="three">
    <div ref="container"></div>
  </div>
</template>

<script setup lang="ts">
// 下面引入便于一步一步教程，自己写全放一个就行了
import {
  WebGLRenderer, //渲染器
  Scene, //场景
  PerspectiveCamera, //相机
  Color,
  PlaneGeometry,
  TextureLoader,
  Clock,
  PointLight, // 颜色转换
} from "three";
import {
  AxesHelper, // 辅助坐标
} from "three";
import {
  Mesh,
  IcosahedronGeometry,
  SpotLight,
  DoubleSide,
  MeshBasicMaterial,
} from "three";
import type { Deps } from "@/ThreeClass/publicDeps";
import { ref, onMounted } from "vue";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

import { TilesRenderer } from "3d-tiles-renderer";
const container = ref<HTMLElement | null>(null); // 插入的dom元素
const scene: Scene = new Scene(); // 场景
const camera = new PerspectiveCamera(60, window.innerWidth / 600, 1, 10000); // 镜头
//camera.position.set(0, 5, 300);
const renderer = new WebGLRenderer(); // 渲染器
const deps = ref<Deps>();
const axisHelper = new AxesHelper(2000);
const clock = new Clock();
const gltfLoader = new GLTFLoader();
const textureLoader = new TextureLoader();

scene.add(axisHelper); // 把创建的坐标体系加入天地！
const light = new PointLight(0xffffff, 30, 100, 50);
light.position.set(0, 10, 10);
scene.add(light);
const needsRerender = ref(false);
const controls = ref();
onMounted(() => {
  initThree();
  renderer.render(scene, camera); // 重新渲染
  camera.position.set(0, 50, 100); //x轴方向观察
  controls.value = new OrbitControls(camera, renderer.domElement);
  controls.value.addEventListener("change", (e) => {
    renderer.render(scene, camera);
  });

  const tilesRenderer = new TilesRenderer("/bpi/3dtit/data/tileset.json");
  tilesRenderer.setCamera(camera);
  tilesRenderer.setResolutionFromRenderer(camera, renderer);
  tilesRenderer.onLoadTileSet = () => (needsRerender.value = true);
  tilesRenderer.onLoadModel = () => (needsRerender.value = true);
  scene.add(tilesRenderer.group);
  function renderLoop() {
    requestAnimationFrame(renderLoop);
    if (needsRerender) {
      needsRerender.value = false;
      camera.updateMatrixWorld();
      tilesRenderer.update();
      renderer.render(scene, camera);
    }
  }
  renderLoop();
});

const initThree = () => {
  scene.background = new Color("#ffffff"); // 设置背景色

  renderer.setSize(window.innerWidth, window.innerHeight);
  (container.value as HTMLElement).appendChild(renderer.domElement); // 载入到dom

  deps.value = { renderer, camera, scene, clock, gltfLoader, textureLoader };
};
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}
.container {
  width: 100%;
  height: 600px;
}
.three {
  &-btn {
    position: absolute;
    top: 0px;
    left: 0;
    padding: 10px;
  }
}
</style>
